package com.clt.ess.web;

import com.clt.ess.CABeen.CheckResultPackage;
import com.clt.ess.base.Constant;
import com.clt.ess.entity.Seal;
import com.clt.ess.entity.SealApply;
import com.clt.ess.gjzw.domain.FileData;
import com.clt.ess.gjzw.domain.FilePackage;
import com.clt.ess.gjzw.domain.SealData;
import com.clt.ess.gjzw.domain.TaskNumData;
import com.clt.ess.gjzw.domain.applyRandom.ApplyRandomRequest;
import com.clt.ess.gjzw.domain.confirmReceipt.ConfirmReceiptRequestData;
import com.clt.ess.gjzw.domain.confirmReceipt.ConfirmReceiptResponseData;
import com.clt.ess.gjzw.domain.revocationSealInfo.RevocationSealInfoCheckResultResponseData;
import com.clt.ess.gjzw.domain.revocationSealInfo.RevocationSealInfoRequestData;
import com.clt.ess.gjzw.domain.updateProtectKey.UpdateProtectKeyRequestData;
import com.clt.ess.gjzw.domain.uploadRecordInfos.UploadRecordInfosRequestData;
import com.clt.ess.service.ICAService;
import com.clt.ess.service.IGjzwService;
import com.clt.ess.service.ISealService;
import com.clt.ess.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

import static com.clt.ess.utils.Base64Utils.encodeBase64File;
import static com.clt.ess.utils.Base64Utils.replaceBlank;
import static com.clt.ess.utils.StringUtils.*;
import static com.clt.ess.utils.dateUtil.getStringDate;
import static java.lang.Thread.sleep;

@Controller
@RequestMapping("test")
public class TestController {

    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session;
    @Autowired
    private ICAService caService;
    @Autowired
    private IGjzwService gjzwService;
    @Autowired
    private ISealService sealService;

    /**
     * 每次拦截到请求会先访问此函数，
     * 获取request,session,response等实例
     *
     * @param request  http请求
     * @param response http回应
     */
    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
        this.session = request.getSession();
    }

    /**
     * 测试政务获取唯一赋码
     *
     * @return
     */
    @RequestMapping(value = "/getSealCode.html", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    @ResponseBody
    private String getSealCode() {

        String sealCode = gjzwService.getSealCode(Constant.applicantCert, "110");
        if (sealCode == null || "".equals(sealCode)) {
            return "获取统一赋码失败";
        }
        return sealCode;
    }

    /**
     * 测试申请证书
     *
     * @return
     */
    @RequestMapping(value = "/CATest.html", method = RequestMethod.GET)
    @ResponseBody
    private String CATest() {

        //获取唯一赋码
//        String sealCode = gjzwService.getSealCode(Constant.applicantCert, "110");
//        if (sealCode == null) {
//            return "获取失败";
//        }
        String OrganizationName = "123456789123456789gjyczmj";
        String CommonName = "110000"+"32432421";
        String publicKey = "BBbr2ZVlcnYvGRUdwnenYiN27E7xh18Nh5brmcyHIPCWWtMqu00dX1qsclgmNTwUGu5yb/YT9MBh92XORkMdqio=";
//        String CommonName = "110000" + sealCode;
//        String publicKey = "BNIbpKXJHAGFGRQHTW8i6FBkkiK+tGGxHeT0cjTjImaEG6ofLt2/umIFQMU9cQbrSEQXeJBftEvd7GPW/OpVphw=";

        CheckResultPackage checkResultPackage = caService.getCertFormCA(OrganizationName, CommonName,
                "1", publicKey, "2019-07-04 22:00:00", "2020-07-04 22:00:00");
        //视图对象
        return checkResultPackage.toString();

    }

    /**
     * 测试吊销证书(ok)
     *
     * @return
     */
    @RequestMapping(value = "/revokeFormCATest.html", method = RequestMethod.GET)
    @ResponseBody
    private String revokeFormCATest() {
        //获取唯一赋码
        String sealCode = gjzwService.getSealCode(Constant.applicantCert, "110");
        if (sealCode == null) {
            return "获取失败";
        }
        String serialNumber = "20031000000774";
        String errorCode = caService.revokeFormCA(serialNumber);
        //视图对象
        return errorCode;
    }

    /**
     * 测试变更证书
     *
     * @return
     */
    @RequestMapping(value = "/changeCertFormCATest.html", method = RequestMethod.GET)
    @ResponseBody
    private String changeCertFormCATest() {

        //获取唯一赋码
        String sealCode = gjzwService.getSealCode(Constant.applicantCert, "110");
        if (sealCode == null) {
            return "获取失败";
        }
        String serialNumber = "20031000000764";
        String certType = "0";
        String OrganizationName = "123456789123456789gjyczmj";
        String CommonName = "11000000001349";
        String subjectPublicKeyInfo = "BBbr2ZVlcnYvGRUdwnenYiN27E7xh18Nh5brmcyHIPCWWtMqu00dX1qsclgmNTwUGu5yb/YT9MBh92XORkMdqio=";

        CheckResultPackage checkResultPackage = caService.changeCertFormCA(serialNumber, certType, OrganizationName, CommonName, subjectPublicKeyInfo);
        //视图对象
        if(checkResultPackage == null){
            return "返回值为空";
        }
        return checkResultPackage.toString();

    }

    /**
     * 测试证书延期
     *
     * @return
     */
    @RequestMapping(value = "/delayCertFormCATest.html", method = RequestMethod.GET)
    @ResponseBody
    private String delayCertFormCATest() {

        //获取唯一赋码
        String sealCode = gjzwService.getSealCode(Constant.applicantCert, "110");
        if (sealCode == null) {
            return "获取失败";
        }
        //用于区分请求列表单个请求的业务编码
        //必须
        String serialNumber = "20031000000764";
        String publicKeyInfo = "BBbr2ZVlcnYvGRUdwnenYiN27E7xh18Nh5brmcyHIPCWWtMqu00dX1qsclgmNTwUGu5yb/YT9MBh92XORkMdqio=";

        CheckResultPackage checkResultPackage = caService.delayCertFormCA(serialNumber,publicKeyInfo);
        if(checkResultPackage == null){
            return "返回值为空";
        }
        //视图对象
        return checkResultPackage.toString();

    }

    /**
     * 印章备案
     * @return
     */
    @RequestMapping(value = "/sealRecord.html", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    @ResponseBody
    private String sealRecord() throws Exception {

        //获取唯一赋码
        String sealCodeData = gjzwService.getSealCode(Constant.applicantCert, "110");
        if (sealCodeData == null) {
            return "获取失败";
        }
        String OrganizationName = "123456789123456789gjyczmj";
        String CommonName = "110000" + sealCodeData;
        String publicKey = "BBbr2ZVlcnYvGRUdwnenYiN27E7xh18Nh5brmcyHIPCWWtMqu00dX1qsclgmNTwUGu5yb/YT9MBh92XORkMdqio=";
        String pub = "Y6w+JNuPzOjXKJ6XzowBt5KzodKxSeKXz/2UixOBaNjh61NqC5gKPv+uVcfHH14eDsPWKgS7jCqT1YwZZ+n0Uw==";
        CheckResultPackage checkResultPackage = caService.getCertFormCA(OrganizationName, CommonName,
                "1", publicKey, "2019-07-04 22:00:00", "2020-07-04 22:00:00");

        String encCert = checkResultPackage.getEncCert();
        String signCert = checkResultPackage.getSignCert();
        String img = replaceBlank(encodeBase64File("/data/1/1.png"));

        String districtCode = "110000";
        List<UploadRecordInfosRequestData> s = new ArrayList<>();
        UploadRecordInfosRequestData uploadRecordInfosRequestData = new UploadRecordInfosRequestData();
        //加密证书
        uploadRecordInfosRequestData.setSealEncCert(encCert);
        //签名证书
        uploadRecordInfosRequestData.setSealSignCert(signCert);
        //行政区划代码
        uploadRecordInfosRequestData.setDistrictCode(districtCode);
        //印章数据
        SealData sealData = new SealData();
        //印章名称
        sealData.setYzmc(getRandom16());
        //印章编码
        sealData.setYzbm(CommonName);
        //印章制作单位编码
        sealData.setYzzzdwbm("TE1100000101100010");
        //印章类型代码
        sealData.setYzlxdm("99");
        //经办人姓名
        sealData.setJbr_xm("213123");
        //经办人证件类型
        sealData.setJbr_zjlx("111");
        //经办人证件号码
        sealData.setJbr_zjhm("123456789987654321");
        //制作日期
        sealData.setZzrq(getStringDate());
        //印模类型
        sealData.setYmlx("png");
        //印模数据
        sealData.setYmsj(img);
        //印章使用单位_单位名称
        sealData.setYzsydw_dwmc("1111111111");
        //印章制作单位_单位名称
        sealData.setYzzzdw_dwmc("222222222222222222");
        //印章使用单位——统一社会信用代码
        sealData.setYzsydw_tyshxydm("TE1100000101100010");

        uploadRecordInfosRequestData.setSealData(sealData);
        s.add(uploadRecordInfosRequestData);
        TaskNumData taskNumData = gjzwService.uploadRecordInfosGetTaskId(Constant.applicantCert, s);
        if (taskNumData == null) {
            return null;
        }
        //下载
        sleep(10000);
        FilePackage filePackage = gjzwService.uploadRecordInfoCheckResult(taskNumData);

        if (sealCodeData == null) {
            return "获取失败";
        }
        return filePackage.toString();
    }
    /**
     * 查询
     *
     * @return
     */
    @RequestMapping(value = "/querySeal.html", method = RequestMethod.GET)
    @ResponseBody
    private String querySeal(String taskId) {
        TaskNumData taskNumData = new TaskNumData();
        taskNumData.setTaskId(taskId);

        FilePackage filePackage = gjzwService.uploadRecordInfoCheckResult(taskNumData);

        return filePackage.toString();
    }
    /**
     * 查询
     *
     * @return
     */
    @RequestMapping(value = "/demo.html",produces = "text/html;charset=UTF-8")
    @ResponseBody
    private String demo(String data) {

       return getDecryptString(getEncryptString(data));
    }
    @RequestMapping(value = "/demo1.html",produces = "text/html;charset=UTF-8")
    @ResponseBody
    private String demo1(String data) {
        return getDecryptString(data);
    }
    @RequestMapping(value = "/demo2.html",produces = "text/html;charset=UTF-8")
    @ResponseBody
    private String demo2(String data) {
        return getEncryptString(data);
    }

    @RequestMapping(value = "/demo4.html",produces = "text/html;charset=UTF-8")
    @ResponseBody
    private String demo4(String keyId) {
        Seal seal = sealService.findSealByKeyId(keyId);
//        boolean aa = sealService.updateSealUKInfo(seal);
        if (seal==null){
            return "sssss";
        }
        return seal.getCertificate().getCerBase64();
    }
    @RequestMapping(value = "/demo5.html",produces = "text/html;charset=UTF-8")
    @ResponseBody
    private String demo5(String keyId) {

        Seal seal = sealService.findSealByKeyId(keyId);
        seal.setSealState(2);
        sealService.updateSeal(seal);
        if (seal==null){
            return "sssss";
        }
        return seal.getCertificate().getCerBase64();
    }
    /**
     * 查询
     * @return
     */
    @RequestMapping(value = "/confirm.html", method = RequestMethod.GET)
    @ResponseBody
    private String confirm(String keyId, String device_code, String EncDeviceCode) {
        keyId = keyId.replace("@@@@", "+");
        //发送回执，入库
        Seal seal = sealService.findSealByKeyId(keyId);
        String taskId = seal.getTaskId();
        List<ConfirmReceiptRequestData> data = new ArrayList<>();
        ConfirmReceiptRequestData confirmReceiptRequestData = new ConfirmReceiptRequestData();
        confirmReceiptRequestData.setTaskId(taskId);
        confirmReceiptRequestData.setDeviceCode(device_code);
        confirmReceiptRequestData.setYzbm(seal.getSeal_code());
        confirmReceiptRequestData.setEncDeviceCode(EncDeviceCode);

        data.add(confirmReceiptRequestData);

        String yzbm = gjzwService.confirmReceiptRequest(Constant.applicantCert, data);
        if (yzbm == null) {
            return "error";
        }
        return yzbm;
    }


    /**
     * 测试印章撤销申请
     *
     * @return
     */
    @RequestMapping(value = "/delete.html", method = RequestMethod.GET)
    @ResponseBody
    private String delete(String keyId)  {
        Seal seal = sealService.findSealByKeyId(keyId);
        List<RevocationSealInfoRequestData> data = new ArrayList<>();
        RevocationSealInfoRequestData revocationSealInfoRequestData = new RevocationSealInfoRequestData();

        revocationSealInfoRequestData.setYzbm(seal.getSeal_code());

        revocationSealInfoRequestData.setDeviceCode(seal.getDevice_code());

        revocationSealInfoRequestData.setEncDeviceCode(seal.getEncDeviceCode());

        data.add(revocationSealInfoRequestData);

        TaskNumData taskNumData =gjzwService.revocationSealInfo(Constant.applicantCert,data);
        if (taskNumData == null){
            return "error";
        }
        seal.setTaskId(taskNumData.getTaskId());
        sealService.updateSeal(seal);
        System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        String yzbm =  gjzwService.revocationSealInfoCheckResult(taskNumData);
        System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        System.out.println(yzbm);
        if (yzbm == null){
            return "error";
        }
        seal.setSealState(2);
        sealService.updateSeal(seal);
        //状态发布系统通知
        return "success";
    }

    /**
     * 测试 撤销申请确认
     *
     * @return
     */
    @RequestMapping(value = "/deleteT.html", method = RequestMethod.GET)
    @ResponseBody
    private String deleteT(String taskId) {
        //发送回执，入库
//      Seal seal = sealService.findSealByKeyId(keyId);
        TaskNumData taskNumData = new TaskNumData();
        taskNumData.setTaskId(taskId);
        String yzbm =  gjzwService.revocationSealInfoCheckResult(taskNumData);
        if (yzbm == null){
            return "error";
        }
        return yzbm;
    }
    /**
     * 测试印章保护密钥更新接口
     * @param keyId
     * @return
     */
    @RequestMapping(value = "/updateProtectKey.html", method = RequestMethod.GET)
    @ResponseBody
    private String updateProtectKey(String keyId)  {

        Seal seal = sealService.findSealByKeyId(keyId);
        List<UpdateProtectKeyRequestData> data  = new ArrayList<>();
        UpdateProtectKeyRequestData updateProtectKeyRequestData = new UpdateProtectKeyRequestData();

        updateProtectKeyRequestData.setDeviceCode(seal.getDevice_code());
        updateProtectKeyRequestData.setEncDeviceCode(seal.getEncDeviceCode());
        updateProtectKeyRequestData.setSealEncCert(seal.getCertificate().getPfxBase64());
        updateProtectKeyRequestData.setSealSignCert(seal.getCertificate().getCerBase64());
        updateProtectKeyRequestData.setYzbm(seal.getSeal_code());

        data.add(updateProtectKeyRequestData);


        TaskNumData taskNumData = gjzwService.updateProtectKey(Constant.applicantCert,data);
        seal.setTaskId(taskNumData.getTaskId());
        //更新任务ID
        sealService.updateSeal(seal);

        Seal seal1 = sealService.findSealByKeyId(keyId);


        FilePackage filePackage =  gjzwService.updateProtectKeyCheckResult(taskNumData);
        if (filePackage == null){
            return "error";
        }
        seal1.setEncFile(filePackage.getEncFile());
        seal1.setDataSymKeyEnc(filePackage.getDataSymKeyEnc());
        seal1.setAppSymKeyEnc(filePackage.getAppSymKeyEnc());

        sealService.updateSealUKInfo(seal1);

        return taskNumData.getTaskId();

    }

    /**
     * 测试印章保护密钥更新接口
     * @param taskId
     * @return
     */
    @RequestMapping(value = "/updateProtectKeyT.html", method = RequestMethod.GET)
    @ResponseBody
    private String updateProtectKeyT(String taskId,String keyId)  {
        Seal seal = sealService.findSealByKeyId(keyId);

        TaskNumData taskNumData = new TaskNumData();
        taskNumData.setTaskId(taskId);
        FilePackage filePackage =  gjzwService.updateProtectKeyCheckResult(taskNumData);
        if (filePackage == null){
            return "error";
        }
        seal.setEncFile(filePackage.getEncFile());
        seal.setDataSymKeyEnc(filePackage.getDataSymKeyEnc());
        seal.setAppSymKeyEnc(filePackage.getAppSymKeyEnc());

        sealService.updateSealUKInfo(seal);
        return "success";
    }



}
